//
//  NetWorkToolsAFN.swift
//  封装AFN
//
//  Created by 代亚洲 on 16/4/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestMethod:String {
    case Post = "post"
    case Get = "get"
}

class NetWorkToolsAFN: AFHTTPSessionManager {
    
//   先创建一个单例
    static let  sharedTolls:NetWorkToolsAFN = {
        let  tolls = NetWorkToolsAFN()
//        添加josn解析方式
        tolls.responseSerializer.acceptableContentTypes?.insert("text/html")
        tolls.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tolls
    }()
    
    
    
    
    // 也可以这样写 可以提高代码的阅读性
    //    取别名swift的写法
    typealias HMRequestCallBack = (responseObject: AnyObject?, error: NSError?)->()
//     func request(method:RequestMethod,url:String,parameters:AnyObject?,finshed:HMRequestCallBack)
    
    
    /// 上传文件
    ///
    /// - parameter method:     请求方式，默认POST
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数
    /// - parameter datas:      要上传的二进制数据
    /// - parameter finished:   请求完成的回调闭包
    func upload(urlString: String, parameters: AnyObject?, datas: [String: NSData], finished: HMRequestCallBack) {
        
        self.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            // 拼装要上传的数据
            for (key, value) in datas {
                formData.appendPartWithFileData(value, name: key, fileName: "aa.png", mimeType: "application/octet-stream")
            }
            }, progress: nil, success: { (_, responseObject) -> Void in
                // 请求成功的回调
                finished(responseObject: responseObject, error: nil)
            }) { (_, error) -> Void in
                finished(responseObject: nil, error: error)
        }
    }
    /**
     请求数据的方法
     - parameter method:     请求方式
     - parameter url:        请求地址
     - parameter parameters: 请求参数
     - parameter finshed:    请求完成回调  返回数据 || 错误
     */
    
    func request(method:RequestMethod,url:String,parameters:AnyObject?,finshed:HMRequestCallBack){
//        成功的回调
        let  success = {(data:NSURLSessionDataTask?,responseObject:AnyObject?)->Void in
            finshed(responseObject: responseObject, error: nil)
        }
//        失败的回调
        let failure = {(data:NSURLSessionDataTask?,error:NSError?)->Void in
            
            finshed(responseObject: nil, error: error)
            }
//        请求方式
        if method == RequestMethod.Get {
            GET(url, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            POST(url, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
}
